package cc.shacocloud.mirage.restful;

import cc.shacocloud.mirage.utils.FutureUtils;
import cc.shacocloud.mirage.utils.collection.SelfSortList;
import cc.shacocloud.mirage.utils.comparator.AnnotationOrderComparator;
import io.vertx.core.Future;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * 基于{@link HandlerExceptionResolver}实现的聚合类，它委托给其他的{@link HandlerExceptionResolver}执行
 */
public class HandlerExceptionResolverComposite implements HandlerExceptionResolver {
    
    private final List<HandlerExceptionResolver> exceptionResolvers = new SelfSortList<>(AnnotationOrderComparator.INSTANCE::getOrder);
    
    /**
     * 设置要委托给的异常解析器列表
     */
    public void addExceptionResolvers(HandlerExceptionResolver... exceptionResolvers) {
        addExceptionResolvers(Arrays.asList(exceptionResolvers));
    }
    
    /**
     * 设置要委托给的异常解析器列表
     */
    public void addExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) {
        this.exceptionResolvers.addAll(exceptionResolvers);
    }
    
    /**
     * 返回要委托的异常解析器列表
     */
    public List<HandlerExceptionResolver> getExceptionResolvers() {
        return Collections.unmodifiableList(this.exceptionResolvers);
    }
    
    /**
     * 通过遍历已配置的异常解析器列表来解析异常
     */
    @Override
    public Future<Object> resolveException(HttpRequest request, HttpResponse response, VertxInvokeHandler handler, Throwable cause) {
        return FutureUtils.sequential(this.exceptionResolvers.iterator(),
                (resolvers, termination) -> {
                    // 解析异常
                    return resolvers.resolveException(request, response, handler, cause)
                            // 返回空的结果表示异常处理器不支持解析
                            .onSuccess(res -> termination.set(res != SKIP));
                });
    }
}
